package com.zhangyu.shadow.repair.delegate.maintain;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.rey.material.app.BottomSheetDialog;
import com.zhangyu.shadow.repair.R;
import com.zhangyu.shadow.repair.R2;
import com.zhangyu.shadow.repair.config.RepairItemType;
import com.zhangyu.shadow.repair.config.RequestUrls;
import com.zhangyu.shadow.repair.config.StateCode;
import com.zhangyu.shadow.repair.delegate.bean.BusBean;
import com.zhangyu.shadow.repair.delegate.bean.DeptBean;
import com.zhangyu.shadow.repair.delegate.bean.ModelPerson;
import com.zhangyu.shadow.repair.delegate.bean.PersonBean;
import com.zhangyu.shadow.repair.delegate.bean.RepairTypeBean;
import com.zhangyu.shadow.repair.delegate.repair.ExpandableItemAdapter;
import com.zhangyu.shadow.repair.delegate.repair.entity.Level0Item;
import com.zhangyu.shadow.repair.delegate.repair.entity.Level1Item;
import com.zhangyu.shadow.repair.delegate.search.entity.MaintainEntity;
import com.zhangyu.shadow.repair.event.TroubleAddEvent;
import com.zhangyu.shadow.repair.intercept.DataIntercept;
import com.zhangyu.shadow.repair.manager.AccountManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;
import st.lib.base.delegate.RxShadowDelegate;
import st.lib.base.net.callback.IError;
import st.lib.base.net.callback.ISuccess;
import st.lib.base.net.rx.RxRestClient;
import st.lib.base.ui.progress.sweetalert.DialogLoader;
import st.lib.base.ui.progress.sweetalert.IDialogClickListener;
import st.lib.base.ui.recycler.MultipleItemEntity;
import st.lib.base.ui.recycler.ObjConverter;
import st.lib.base.util.utilcode.util.ScreenUtils;
import st.lib.base.util.utilcode.util.ToastUtils;

/**
 * @author zhangyu
 * @date 2018/2/23
 */

@SuppressWarnings("ALL")
public class MaintainDelegate extends RxShadowDelegate {
    private static final String ENTITY = "entity";

    public static MaintainDelegate create(MultipleItemEntity entity) {
        final MaintainDelegate contentDelegate = new MaintainDelegate();
        final Bundle bundle = new Bundle();
        bundle.putSerializable(ENTITY, entity);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.tv_plan_repair_date)
    TextView mTvPlanRepairDate;
    @BindView(R2.id.tv_repair_date)
    TextView mTvRepairDate;
    @BindView(R2.id.tv_factory_date)
    TextView mTvFactoryDate;
    @BindView(R2.id.tv_repair_time)
    TextView mTvRepairTime;
    @BindView(R2.id.tv_factory_time)
    TextView mTvFactoryTime;
    @BindView(R2.id.tv_out_date)
    TextView mTvOutDate;
    @BindView(R2.id.tv_out_time)
    TextView mTvOutTime;
    @BindView(R2.id.str_plan_repair_time)
    TextView mTvPlanRepairTime;
    @BindView(R2.id.tv_actual_start_date)
    TextView mTvActualStartDate;
    @BindView(R2.id.tv_actual_start_time)
    TextView mTvActualStartTime;
    @BindView(R2.id.tv_actual_end_date)
    TextView mTvActualEndDate;
    @BindView(R2.id.tv_actual_end_time)
    TextView mTvActualEndTime;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.layout_out_time)
    LinearLayout mLayoutOutTime;
    @BindView(R2.id.layout_actual_start_time)
    LinearLayout mLayoutActualStartTime;
    @BindView(R2.id.layout_actual_end_time)
    LinearLayout mLayoutActualEndTime;
    @BindView(R2.id.button_confirm)
    Button mBtnConfirm;
    @BindView(R2.id.tv_maintain_type)
    TextView mTvMaintainType;
    @BindView(R2.id.tv_bus_number)
    TextView mTvBusNumber;
    @BindView(R2.id.tv_bus_line)
    TextView mTvLine;
    @BindView(R2.id.tv_person)
    TextView mTvPerson;
    private ExpandableItemAdapter mItemAdapter;
    private MaintainEntity mItemEntity;
    private String mState;
    private DialogLoader mDialogLoader;
    private MultiPersonDialog mMultiPersonDialog;
    private RepairTypeDialog mRepairTypeDialog;
    //0小修 1保养
    private int mType;
    private List<RepairTypeBean> mRepairTypeList = new ArrayList<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle bundle = getArguments();
        if (bundle != null) {
            MultipleItemEntity multipleItemEntity = (MultipleItemEntity) bundle.getSerializable(ENTITY);
            mItemEntity = multipleItemEntity != null ?
                    (MaintainEntity) multipleItemEntity.getField(RepairItemType.ITEM_MAINTAIN) : new MaintainEntity();
            mType = multipleItemEntity.getItemType() == RepairItemType.ITEM_TYPE_MAINTAIN ? 1 : 0;
            mState = mItemEntity != null ? mItemEntity.getWorkStatusCode() : "";
        }
    }

    @Override
    public Object setLayout() {
        if (ScreenUtils.isPad(_mActivity)) {
            return R.layout.delegate_maintain;
        } else {
            return R.layout.delegate_maintain_phone;
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        initView();
    }

    private void initView() {

        if (mDialogLoader == null) {
            mDialogLoader = new DialogLoader(getContext());
        }
        setViewState(mState);
        mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
        if (mItemEntity != null) {
            if (mType == 0) {
                //小修无计划时间
                mTvPlanRepairDate.setVisibility(View.GONE);
                mTvPlanRepairTime.setVisibility(View.GONE);
            } else {
                mTvPlanRepairDate.setText(mItemEntity.getPlanStartTime());
            }
            mTvMaintainType.setText(mType == 1 ? mItemEntity.getMaintenanceTypeName() :
                    "小修");
            mTvBusNumber.setText(mItemEntity.getVehicleCode());
            mTvLine.setText(mItemEntity.getRouteName());
            mTvPerson.setText(mItemEntity.getReportPersonName());
            mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

            mItemAdapter = new ExpandableItemAdapter(this, new MaintainDataConverter()
                    .converter(mItemEntity.getWorkStatusCode(), mItemEntity.getListClassification()));
            mRecyclerView.setAdapter(mItemAdapter);
            mItemAdapter.expandAll();
        }
        EventBus.getDefault().register(this);
        getRepairType();
    }

    private void getRepairType() {
        RxRestClient.builder()
                .url(RequestUrls.URL_BASE_REPAIR_TYPE)
                .params(AccountManager.getInstance().getBaseInfo())
                .interceptor(new DataIntercept())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        List<RepairTypeBean> list = new ObjConverter<ArrayList<RepairTypeBean>>().convert(response
                                , new TypeReference<ArrayList<RepairTypeBean>>() {
                                });
                        if (list != null && !list.isEmpty()) {
                            mRepairTypeList.clear();
                            mRepairTypeList.addAll(list);
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                })
                .build()
                .post();
    }


    private void setViewState(String type) {
        try {
            switch (type) {
                case StateCode.FINISH_PLAN:
                    mToolbar.setTitle(mItemEntity.getVehicleCode() + "    报修登记");
                    mBtnConfirm.setText("提交");
                    mLayoutOutTime.setVisibility(View.INVISIBLE);
                    String[] repairDateTime = getNowDateTime();
                    mTvRepairDate.setText(repairDateTime[0]);
                    mTvRepairTime.setText(repairDateTime[1]);
                    mTvFactoryDate.setText(repairDateTime[0]);
                    mTvFactoryTime.setText(repairDateTime[1]);
                    mLayoutActualStartTime.setVisibility(View.GONE);
                    mLayoutActualEndTime.setVisibility(View.GONE);
                    break;
                case StateCode.READY_WORK:
                    if (mType == 0) {
                        //小修
                        mBtnConfirm.setText("删除");
                        mBtnConfirm.setEnabled(true);
                    } else {
                        mBtnConfirm.setText("已登记");
                        mBtnConfirm.setEnabled(false);
                    }
                    mLayoutOutTime.setVisibility(View.INVISIBLE);
                    mLayoutActualStartTime.setVisibility(View.GONE);
                    mLayoutActualEndTime.setVisibility(View.GONE);
                    setDateTimeState();
                    break;
                case StateCode.UNDER_WORK:
                    if (mType == 0) {
                        //小修
                        mBtnConfirm.setText("删除");
                        mBtnConfirm.setEnabled(true);
                    } else {
                        mBtnConfirm.setText("处理中");
                        mBtnConfirm.setEnabled(false);
                    }
                    mLayoutOutTime.setVisibility(View.INVISIBLE);
                    mLayoutActualStartTime.setVisibility(View.GONE);
                    mLayoutActualEndTime.setVisibility(View.GONE);
                    setDateTimeState();
                    break;
                case StateCode.COMPLETED_WORK:
                    mLayoutOutTime.setVisibility(View.VISIBLE);
                    mBtnConfirm.setText("确认交车");
                    String[] outDateTime = getNowDateTime();
                    mTvOutDate.setText(outDateTime[0]);
                    mTvOutTime.setText(outDateTime[1]);
                    mLayoutActualStartTime.setVisibility(View.VISIBLE);
                    mLayoutActualEndTime.setVisibility(View.VISIBLE);
                    setDateTimeState();
                    break;
                case StateCode.FINISH_WORK:
                    mBtnConfirm.setText("已交车");
                    mLayoutOutTime.setVisibility(View.VISIBLE);
                    mTvOutDate.setEnabled(false);
                    mTvOutTime.setEnabled(false);
                    mBtnConfirm.setEnabled(false);
                    mTvOutDate.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    mTvOutTime.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    String outTime = mItemEntity.getOutFactoryTime();
                    String[] outDateTime2 = outTime.split(" ");
                    mTvOutDate.setText(outDateTime2[0]);
                    mTvOutTime.setText(outDateTime2[1]);
                    mLayoutActualStartTime.setVisibility(View.VISIBLE);
                    mLayoutActualEndTime.setVisibility(View.VISIBLE);
                    setDateTimeState();
                    break;
                default:
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String[] getNowDateTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String dateString = simpleDateFormat.format(new Date());
        return dateString.split(" ");
    }


    private void setDateTimeState() {
        mToolbar.setTitle(mItemEntity.getVehicleCode() + "    报修详情");
        String repairTime = mItemEntity.getTroubleTime();
        String[] repairDateTime = null;
        if (repairTime != null) {
            repairDateTime = repairTime.split(" ");
        }
        String factoryTime = mItemEntity.getInFactoryTime();
        String[] factoryDateTime = null;
        if (factoryTime != null) {
            factoryDateTime = factoryTime.split(" ");
        }
        String actualStartTime = mItemEntity.getActualStartTime();
        String[] actualStartDateTime = null;
        if (actualStartTime != null) {
            actualStartDateTime = actualStartTime.split(" ");
        }
        String actualEndTime = mItemEntity.getActualEndTime();
        String[] actualEndDateTime = null;
        if (actualEndTime != null) {
            actualEndDateTime = actualEndTime.split(" ");
        }
        mTvRepairDate.setEnabled(false);
        mTvRepairTime.setEnabled(false);
        mTvFactoryDate.setEnabled(false);
        mTvFactoryTime.setEnabled(false);
        mTvRepairDate.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        mTvRepairTime.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        mTvFactoryDate.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        mTvFactoryTime.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));

        if ("true".equals(AccountManager.getInstance().getCanEditTime())) {
            //可以修改开完工时间
            if (mState.equals(StateCode.FINISH_WORK)) {
                mTvActualStartDate.setEnabled(false);
                mTvActualStartTime.setEnabled(false);
                mTvActualEndDate.setEnabled(false);
                mTvActualEndTime.setEnabled(false);
                mTvActualStartDate.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                mTvActualStartTime.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                mTvActualEndDate.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                mTvActualEndTime.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            }
        } else {
            mTvActualStartDate.setEnabled(false);
            mTvActualStartTime.setEnabled(false);
            mTvActualEndDate.setEnabled(false);
            mTvActualEndTime.setEnabled(false);
            mTvActualStartDate.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            mTvActualStartTime.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            mTvActualEndDate.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            mTvActualEndTime.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        }
        if (repairDateTime != null && repairDateTime.length > 1) {
            mTvRepairDate.setText(repairDateTime[0]);
            mTvRepairTime.setText(repairDateTime[1]);
        } else {
            mTvRepairDate.setText("");
            mTvRepairTime.setText("");
        }
        if (actualStartDateTime != null && actualStartDateTime.length > 1) {
            mTvActualStartDate.setText(actualStartDateTime[0]);
            mTvActualStartTime.setText(actualStartDateTime[1]);
        }
        if (actualEndDateTime != null && actualEndDateTime.length > 1) {
            mTvActualEndDate.setText(actualEndDateTime[0]);
            mTvActualEndTime.setText(actualEndDateTime[1]);
        }
        mTvFactoryDate.setText(factoryDateTime[0]);
        mTvFactoryTime.setText(factoryDateTime[1]);
    }

    @OnClick({R2.id.tv_repair_date,
            R2.id.tv_factory_date,
            R2.id.tv_out_date,
            R2.id.tv_actual_start_date,
            R2.id.tv_actual_end_date})
    public void onModifiDate(View view) {
        final int id = view.getId();
        final Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                String date = year + "-" + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) +
                        "-" + (dayOfMonth < 10 ? ("0" + dayOfMonth) : dayOfMonth);
                if (id == R.id.tv_repair_date) {
                    mTvRepairDate.setText(date);
                } else if (id == R.id.tv_factory_date) {
                    mTvFactoryDate.setText(date);
                } else if (id == R.id.tv_out_date) {
                    mTvOutDate.setText(date);
                } else if (id == R.id.tv_actual_start_date) {
                    mTvActualStartDate.setText(date);
                } else if (id == R.id.tv_actual_end_date) {
                    mTvActualEndDate.setText(date);
                }
            }
        },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    @OnClick({R2.id.tv_repair_time,
            R2.id.tv_factory_time,
            R2.id.tv_out_time,
            R2.id.tv_actual_start_time,
            R2.id.tv_actual_end_time})
    public void onModifiTime(View view) {
        final int id = view.getId();
        final Calendar calendar = Calendar.getInstance();
        TimePickerDialog dialog = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                String time = (hourOfDay < 10 ? ("0" + hourOfDay) : hourOfDay)
                        + ":" + (minute < 10 ? ("0" + minute) : (minute));
                if (id == R.id.tv_repair_time) {
                    mTvRepairTime.setText(time);
                } else if (id == R.id.tv_factory_time) {
                    mTvFactoryTime.setText(time);
                } else if (id == R.id.tv_out_time) {
                    mTvOutTime.setText(time);
                } else if (id == R.id.tv_actual_start_time) {
                    mTvActualStartTime.setText(time);
                } else if (id == R.id.tv_actual_end_time) {
                    mTvActualEndTime.setText(time);
                }
            }
        },
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true);
        dialog.show();
    }

    @Subscribe
    public void onTroubleAddEvent(TroubleAddEvent event) {
        int position = event.mPosition;
        List<MultipleItemEntity> list = event.mItemEntities;
        final Level0Item lv0 = (Level0Item) mItemAdapter.getItem(position);
        ArrayList<Level1Item> level1Items = new ArrayList<>();
        level1Items.add(new Level1Item(list));
        if (lv0 != null) {
            lv0.setSubItems(level1Items);
        }

        final Level1Item lv1 = (Level1Item) mItemAdapter.getItem(position + 1);
        if (lv1 != null) {
            lv1.setMultiItemEntities(list);
        }

        mItemAdapter.notifyItemChanged(position);
        mItemAdapter.notifyItemChanged(position + 1);
    }

    @OnClick(R2.id.button_confirm)
    public void onConfirm() {
        if (mState.equals(StateCode.FINISH_PLAN) ||
                mState.equals(StateCode.COMPLETED_WORK)) {
            final View view = getLayoutInflater().inflate(R.layout.view_dialog_input, null);
            final BottomSheetDialog mDialog = new BottomSheetDialog(getContext());
            mDialog.applyStyle(R.style.MyBottomSheetDialogStyle)
                    .contentView(view)
                    .cancelable(true)
                    .show();
            final EditText editText = view.findViewById(R.id.et_code);
            editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (editText.getText().toString().length() == 0) {
                        ToastUtils.showShortSafe("请输入工号");
                    } else {
                        mDialog.cancel();
                        sendData(editText.getText().toString());
                    }
                    return false;
                }
            });
            final com.rey.material.widget.Button button = view.findViewById(R.id.button_confirm);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (editText.getText().toString().length() == 0) {
                        ToastUtils.showShortSafe("请输入工号");
                    } else {
                        mDialog.cancel();
                        sendData(editText.getText().toString());
                    }

                }
            });
        } else if (mState.equals(StateCode.READY_WORK) ||
                mState.equals(StateCode.UNDER_WORK)) {
            if (mType == 0) {
                //小修删除保修
                new DeleteDialog(_mActivity, new DeleteDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm(String reason) {
                        mDialogLoader.showProgressDialog(true, "正在删除", "请稍候...");
                        mDisposables.add(RxRestClient.builder().url("repair/change")
                                .params("vmAction", 251)
                                .params("userType", 2)
                                .params("remark", reason)
                                .params("sourceApp", "交接车app")
                                .params("vmId", mItemEntity.getId())
                                .params(AccountManager.getInstance().getBaseInfo())
                                .success(new ISuccess() {
                                    @Override
                                    public void onSuccess(String response) {
                                        mDialogLoader.stopProgressWithSuccess("删除成功", "请确认",
                                                new IDialogClickListener() {
                                                    @Override
                                                    public void onClick() {
                                                        mDialogLoader.clearDialog();
                                                        pop();
                                                    }
                                                });
                                    }
                                }).error(new IError() {
                                    @Override
                                    public void onError(int code, String msg) {
                                        mDialogLoader.stopProgressWithFailed("删除失败", msg);
                                    }
                                }).build().post());
                    }
                }).show();
            }
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private void sendData(String key) {
        mDialogLoader.showProgressDialog(true, "正在搜索", "请稍候...");
        mDisposables.add(RxRestClient.builder().url("/person/searchPerson")
                .params("queryParam", key)
                .params(AccountManager.getInstance().getBaseInfo())
                .interceptor(new DataIntercept())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        if (!TextUtils.isEmpty(response)) {
                            JSONArray jsonArray = JSONArray.parseArray(response);
                            if (jsonArray.size() > 0 && jsonArray.size() < 2) {
                                final JSONObject jsonObject = jsonArray.getJSONObject(0);
                                final int id = jsonObject.getInteger("id");
                                final String code = jsonObject.getString("code");
                                final String name = jsonObject.getString("name");
                                final String phoneNo = jsonObject.getString("phoneNo");
                                mDialogLoader.stopProgressWithWarning("提示", "驾驶员姓名：" + name + "\n驾驶员工号：" + code, new IDialogClickListener() {
                                    @Override
                                    public void onClick() {
                                        if (phoneNo == null || phoneNo.isEmpty()) {
                                            new InputPhoneNumberDialog(_mActivity, new InputPhoneNumberDialog.OnActionListener() {
                                                @Override
                                                public void onDone(String number) {
                                                    //提交号码
                                                    if (number != null && !number.isEmpty()) {
                                                        RxRestClient.builder()
                                                                .url("person/setPersonInfo")
                                                                .body(RequestBody.create(
                                                                        okhttp3.MediaType.parse("application/json; charset=utf-8"),
                                                                        PostPhoneData.getJsonData(
                                                                                AccountManager.getInstance().getAppId(),
                                                                                AccountManager.getInstance().getAuthKey(),
                                                                                AccountManager.getInstance().getWorkCode(),
                                                                                AccountManager.getInstance().getSourceType(),
                                                                                new ModelPerson(id, number))))
                                                                .build().flatPostRaw().subscribeOn(Schedulers.io())
                                                                .observeOn(AndroidSchedulers.mainThread())
                                                                .subscribeWith(new DisposableObserver<String>() {
                                                                    @Override
                                                                    public void onNext(String s) {

                                                                    }

                                                                    @Override
                                                                    public void onError(Throwable e) {

                                                                    }

                                                                    @Override
                                                                    public void onComplete() {

                                                                    }
                                                                });
                                                    }
                                                    mDialogLoader.clearDialog();
                                                    if (mDialogLoader != null) {
                                                        mDialogLoader.changeToProgressType("正在提交...");
                                                    }
                                                    commitInfo(id, code, name);
                                                }
                                            }).show();
                                        } else {
                                            if (mDialogLoader != null) {
                                                mDialogLoader.changeToProgressType("正在提交...");
                                            }
                                            commitInfo(id, code, name);
                                        }

                                    }
                                });
                                return;
                            } else if (jsonArray.size() > 1) {
                                //多个人
                                mDialogLoader.clearDialog();
                                List<PersonBean> personBeans = new ArrayList<>();
                                for (int i = 0, size = jsonArray.size(); i < size; i++) {
                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                    PersonBean personBean = new PersonBean();
                                    personBean.setId(jsonObject.getInteger("id"));
                                    personBean.setCode(jsonObject.getString("code"));
                                    personBean.setName(jsonObject.getString("name"));
                                    personBean.setBirthDay(jsonObject.getString("birthDay"));
                                    personBeans.add(personBean);
                                }
                                if (mMultiPersonDialog == null) {
                                    mMultiPersonDialog = new MultiPersonDialog(_mActivity, personBeans,
                                            new MultiPersonDialog.OnConfirmListener() {
                                                @Override
                                                public void onConfirm(final PersonBean personBean) {
                                                    if (personBean.getPhoneNo() == null ||
                                                            personBean.getPhoneNo().isEmpty()) {
                                                        new InputPhoneNumberDialog(_mActivity, new InputPhoneNumberDialog.OnActionListener() {
                                                            @Override
                                                            public void onDone(String number) {
                                                                //提交号码
                                                                if (number != null && !number.isEmpty()) {
                                                                    RxRestClient.builder()
                                                                            .url("person/setPersonInfo")
                                                                            .body(RequestBody.create(
                                                                                    okhttp3.MediaType.parse("application/json; charset=utf-8"),
                                                                                    PostPhoneData.getJsonData(
                                                                                            AccountManager.getInstance().getAppId(),
                                                                                            AccountManager.getInstance().getAuthKey(),
                                                                                            AccountManager.getInstance().getWorkCode(),
                                                                                            AccountManager.getInstance().getSourceType(),
                                                                                            new ModelPerson(personBean.getId(), number))))
                                                                            .interceptor(new DataIntercept())
                                                                            .build().flatPostRaw().subscribeOn(Schedulers.io())
                                                                            .observeOn(AndroidSchedulers.mainThread()).subscribeWith(new DisposableObserver<String>() {
                                                                        @Override
                                                                        public void onNext(String s) {

                                                                        }

                                                                        @Override
                                                                        public void onError(Throwable e) {

                                                                        }

                                                                        @Override
                                                                        public void onComplete() {

                                                                        }
                                                                    });
                                                                }
                                                                mDialogLoader.showProgressDialog(true,
                                                                        "正在提交", "请稍后..");
                                                                commitInfo(personBean.getId(), personBean.getCode(),
                                                                        personBean.getName());
                                                            }
                                                        }).show();
                                                    } else {
                                                        if (mDialogLoader != null) {
                                                            mDialogLoader.changeToProgressType("正在提交...");
                                                        }
                                                        commitInfo(personBean.getId(), personBean.getCode(),
                                                                personBean.getName());
                                                    }

                                                }
                                            });
                                    mMultiPersonDialog.show();
                                } else {
                                    mMultiPersonDialog.setRadioGroup(personBeans);
                                    mMultiPersonDialog.show();
                                }
                            } else {
                                mDialogLoader.stopProgressWithWarning("提示", "未查询到驾驶员信息", new IDialogClickListener() {
                                    @Override
                                    public void onClick() {
                                        mDialogLoader.clearDialog();
                                    }
                                });
                            }
                        } else {
                            mDialogLoader.stopProgressWithWarning("提示", "未查询到驾驶员信息", new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.clearDialog();
                                }
                            });
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogLoader.stopProgressWithWarning("提示", "未查询到驾驶员信息", new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mDialogLoader.clearDialog();
                            }
                        });
                    }
                })
                .build()
                .post());
    }

    private void commitInfo(int id, String code, String name) {
        if (mState.equals(StateCode.FINISH_PLAN)) {
            final PostReportData reportData = PostReportData
                    .getPostReportData(mItemEntity.getId(),
                            mItemEntity.getVehicleCode(),
                            id, code, name, mItemAdapter);
            //报修时间
            reportData.setReportTime(mTvRepairDate.getText().toString() + " " + mTvRepairTime
                    .getText().toString());
            reportData.setInFactoryTime(mTvFactoryDate.getText().toString() + " " + mTvFactoryTime
                    .getText().toString());
            if (mType == 0) {
                //小修报修需要设置厂 和组
                reportData.setDept(new DeptBean(AccountManager.getInstance()
                        .getDepId(), null, null));
                reportData.setShiftGroup(new DeptBean(AccountManager.getInstance()
                        .getGroupId(), null, null));
                //选择小修类型
                if (mRepairTypeList != null && !mRepairTypeList.isEmpty()) {
                    mDialogLoader.clearDialog();
                    if (mRepairTypeDialog == null) {
                        mRepairTypeDialog = new RepairTypeDialog(_mActivity, mRepairTypeList, new RepairTypeDialog.OnConfirmListener() {
                            @Override
                            public void onConfirm(RepairTypeBean repairTypeBean) {
                                reportData.setRepairTypeReal(repairTypeBean);
                                //交车
                                String bodyString = PostJsonReportData.getJsonData(null,
                                        reportData,
                                        AccountManager.getInstance().getAppId(),
                                        AccountManager.getInstance().getAuthKey(),
                                        AccountManager.getInstance().getWorkCode(),
                                        AccountManager.getInstance().getSourceType(), 202);
                                mDialogLoader.showProgressDialog(true,
                                        "正在提交", "请稍后..");
                                postData(bodyString);
                            }

                            @Override
                            public void onHide() {
                                mDialogLoader.clearDialog();
                            }
                        });
                        mRepairTypeDialog.show();
                    } else {
                        mRepairTypeDialog.setRadioGroup(mRepairTypeList);
                        mRepairTypeDialog.show();
                    }
                } else {
                    String bodyString = PostJsonReportData.getJsonData(null,
                            reportData,
                            AccountManager.getInstance().getAppId(),
                            AccountManager.getInstance().getAuthKey(),
                            AccountManager.getInstance().getWorkCode(),
                            AccountManager.getInstance().getSourceType(), 202);
                    postData(bodyString);
                }
            } else {
                //保养报修
                String bodyString = PostJsonReportData.getJsonData(reportData, null,
                        AccountManager.getInstance().getAppId(),
                        AccountManager.getInstance().getAuthKey(),
                        AccountManager.getInstance().getWorkCode(),
                        AccountManager.getInstance().getSourceType(), 102);
                postData(bodyString);
            }
        } else {
            //接车
            PostOutFactoryData postOutFactoryData =
                    new PostOutFactoryData(mItemEntity.getId(),
                            mTvOutDate.getText().toString()
                                    + " " + mTvOutTime.getText().toString(),
                            Integer.parseInt(AccountManager.getInstance().getWorkId()),
                            AccountManager.getInstance().getWorkCode(),
                            AccountManager.getInstance().getWorkName(),
                            new PostReportData.DriverBean()
                                    .setId(id).setName(name).setCode(code),
                            mTvActualStartDate.getText().toString()
                                    + " " + mTvActualStartTime.getText().toString(),
                            mTvActualEndDate.getText().toString()
                                    + " " + mTvActualEndTime.getText().toString());
            String bodyString = PostJsonOutFactoryData.getJsonData(mType == 0 ? null : postOutFactoryData,
                    mType == 0 ? postOutFactoryData : null,
                    AccountManager.getInstance().getAppId(),
                    AccountManager.getInstance().getAuthKey(),
                    AccountManager.getInstance().getWorkCode(),
                    AccountManager.getInstance().getSourceType(),
                    mType == 1 ? 106 : 206);
            postData(bodyString);
        }
    }

    private void postData(String bodyString) {
        Log.e("body", bodyString);
        mDisposables.add(RxRestClient.builder().url(
                mType == 0 ? "/repair/save" :
                        "/maintenance/save")
                .body(RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), bodyString))
                .interceptor(new DataIntercept())
                .build()
                .flatPostRaw()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {

                    @Override
                    public void onNext(String response) {

                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int resultCode = jsonObject.getInteger("resultCode");
                        String object = jsonObject.getString("result");
                        String resultMsg = jsonObject.getString("resultMsg");
                        if (resultCode == RxRestClient.SUCCESS_CODE) {
                            mDialogLoader.stopProgressWithSuccess(
                                    mState.equals(StateCode.FINISH_PLAN) ? "报修成功" : "交车成功", null,
                                    new IDialogClickListener() {
                                        @Override
                                        public void onClick() {
                                            if (mItemEntity != null && mState.equals(StateCode.FINISH_PLAN)) {
                                                BusBean busBean = new BusBean();
                                                busBean.setId(mItemEntity.getId());
                                                busBean.setVehicleCode(mItemEntity.getVehicleCode());
                                                AccountManager.getInstance().addRepairBus(
                                                        mType, busBean
                                                );
                                            }
                                            mDialogLoader.clearDialog();
                                            pop();
                                        }
                                    });
                        } else {
                            mDialogLoader.stopProgressWithFailed("提示", resultMsg, new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.clearDialog();
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mDialogLoader.stopProgressWithFailed("提示", e.getMessage(), new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mDialogLoader.clearDialog();
                            }
                        });
                    }

                    @Override
                    public void onComplete() {

                    }
                }));
    }

    @Override
    public boolean onBackPressedSupport() {
        if (!isFastClick()) {
            pop();
        }
        return true;
    }

}
